#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
#include<string>


using namespace std;


int main()
{
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0)
    {
        cout << "socket failed" << endl;
    }

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = ntohs(8080);
    server.sin_addr.s_addr = inet_addr("116.204.104.202");
    socklen_t len = sizeof(server);
    while (true)
    {
        char buffer[1024];
        cout << "client send: ";
        cin >> buffer;
        ssize_t n = sendto(fd, buffer, sizeof(buffer), 0, (struct sockaddr*)&server, len);
        if (n < 0)
        {
            cout << "sendto failed" << endl;
            return 1;
        }
        else if (n == 0)
        {
            cout << "server closed,me too!" << endl;
            close(fd);
            return 1;
        }
        char str[1024];
        ssize_t b = recvfrom(fd, str, sizeof(str), 0, (struct sockaddr*)&server, &len);
        if (b < 0)
        {
            cout << "recv failed" << endl;
            close(fd);
            return 1;
        }
        else if (b == 0)
        {
            cout << "server close ,me too!" << endl;
            return 0;
        }
        else
        {
            str[b] = 0;
            cout << "client recv: " << str << endl;
        }

    }
    return 0;
}